const article = require("../models/Article");

var chokidar = require("chokidar");
var watcher = null;
var ready = false;

var fs = require("fs");
var md2json = require("md-2-json");
const moment = require("moment");

module.exports.watch = function () {
    // 新增文件时
    function addFileListener(path_) {
        if (ready) {
            console.log("File", path_, "has been added");
            addArticle(path_);
        }
    }
    function addDirecotryListener(path) {
        if (ready) {
            console.log("Directory", path, "has been added");
        }
    }

    // 文件内容变化时
    function fileChangeListener(path_) {
        console.log("File", path_, "has been changed");
        modifyArticles(path_);
    }

    // 删除文件时，需要把文件里所有的用例删掉
    function fileRemovedListener(path_) {
        console.log("File", path_, "has been removed");
    }

    // 删除目录时
    function directoryRemovedListener(path) {
        console.log("Directory", path, "has been removed");
    }

    if (!watcher) {
        watcher = chokidar.watch("blogs");
    }

    watcher
        .on("add", addFileListener)
        .on("addDir", addDirecotryListener)
        .on("change", fileChangeListener)
        .on("unlink", fileRemovedListener)
        .on("unlinkDir", directoryRemovedListener)
        .on("error", function (error) {
            log.info("Error happened", error);
        })
        .on("ready", function () {
            console.log("Initial scan complete. Ready for changes.");
            ready = true;
        });

    // 解析 warkdown 为 JSON
    async function parsingArticles(path_) {
        let pathReplace = path_.replace(/\\/g, "/");
        let path = "./" + pathReplace;
        let stat = fs.statSync(path_);
        let articleObj;

        await fs.promises
            .readFile(path)
            .then(function (result) {
                articleObj = md2json.parse(result.toString());
            })
            .catch(function (error) {
                console.log(error);
            });

        // 处理文章字段
        return processingField(stat, articleObj, pathReplace);
    }

    // 处理文章字段的方法
    function processingField(stat, articleObj, pathReplace) {
        let articleData = {
            idNo: null,
            title: "",
            tags: [],
            publishTime: "",
            publishMonth: "",
            publishDay: "",
            mainText: "",
            minorText: "",
            minorSecdText: "",
            comments: "",
            readingTime: 0,
        };
        // 获取文章发表日期
        let pubTime = moment(stat.birthtime).format("YYYY·MM·DD");
        articleData.publishTime = pubTime;
        let month = pubTime.split("·")[1];
        if (month[0] == "0") {
            articleData.publishMonth = month.slice(1);
        } else {
            articleData.publishMonth = month;
        }
        articleData.publishDay = pubTime.split("·")[2];
        // 获取文章 Id
        let pathRe = pathReplace.split(".")[0];
        articleData.idNo = Number(pathRe.match(/#(\S*)/)[1]);
        // 获取文章标题、内容等
        articleData.title = articleObj.title.raw.split("\n")[0];
        articleData.tags = articleObj.tags.raw.split("\n")[0].split("、");
        articleData.mainText = articleObj.content.raw;
        articleData.minorText = articleObj.content.raw.split("\n")[0];
        articleData.minorSecdText = articleObj.content.raw.split("\n")[1];
        // 获取文章字数，计算阅读时间
        let size = 0;
        for (let key in articleObj) {
            size = size + articleObj[key].raw.length;
        }
        articleData.readingTime = Math.round(size / 300);

        return articleData;
    }

    // 新增文章
    async function addArticle(path_) {
        let dataBody = await parsingArticles(path_);

        article.create(dataBody, function (err, data) {
            if (err) {
                return err;
            }
            console.log("新增成功", data);
        });
    }

    // 修改文章
    async function modifyArticles(path_) {
        let dataBody = await parsingArticles(path_);

        article.findOneAndUpdate(
            { idNo: dataBody.idNo },
            dataBody,
            null,
            function (err, data) {
                if (err) {
                    return err;
                }
                console.log("修改成功", data);
            }
        );
    }
};
